<?php

namespace app\controllers;

use app\models\News;
use Yii;
use yii\base\Exception;
use yii\web\Controller;
use yii\web\Response;

class DefaultController extends Controller
{
    public function actionIndex()
    {
        $new_info = News::find()->where(['new_type' => 3])->orderBy(['new_weight' => SORT_DESC])->limit(4)->all();
        $pro_info = News::find()->where(['new_type' => 2])->orderBy(['new_weight' => SORT_DESC])->limit(4)->all();
        return $this->render('index', ['info' => $new_info, 'pro_info' => $pro_info]);
    }

    public function actionGetType()
    {
        Yii::$app->response->format = Response::FORMAT_JSON;
        $type_car = News::find()->select(['new_title', 'new_content', 'new_img'])->where(['new_type' => 1])->orderBy(['new_weight' => SORT_DESC])->asArray()->one();
        $type_product = News::find()->select(['new_title', 'new_content', 'new_img'])->where(['new_type' => 2])->orderBy(['new_weight' => SORT_DESC])->asArray()->one();
        $type_company = News::find()->select(['new_title', 'new_content', 'new_img'])->where(['new_type' => 3])->orderBy(['new_weight' => SORT_DESC])->asArray()->one();
        $type_live = News::find()->select(['new_title', 'new_content', 'new_img'])->where(['new_type' => 4])->orderBy(['new_weight' => SORT_DESC])->asArray()->one();
        $type_car['href'] = '/car-info/index';
        $type_product['href'] = '/car-info/activity';
        $type_company['href'] = '/car-info/product';
        $type_live['href'] = '/car-info/live';
        $type_arr = [];
        array_push($type_arr, $type_car, $type_product, $type_company, $type_live);
        return ['code' => 200, 'type' => $type_arr];
    }

    public function actionGetBanner()
    {
        Yii::$app->response->format = Response::FORMAT_JSON;
        try {
            $banner_info = News::find()->select(['new_img', 'id'])->where(['new_type' => 3])->orderBy(['new_weight' => SORT_DESC])->limit(4)->all();
            return ['code' => 200, 'banner' => $banner_info];
        } catch (Exception $e) {
            return ['code' => -200, 'msg' => $e->getMessage()];
        }
    }
}
